<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-1-19
 * Time: 下午5:15
 */

namespace console\modules\others\controllers;


use common\models\CarOrder;
use common\models\credit_app\ApiLog;
use common\models\ManualPics;
use yii\console\Controller;
use yii\db\Exception;

class DbController extends Controller
{
    /**
     * api_log表添加l_uid字段
     * php yii others/db/set-api-log-uid
     */
    public function actionSetApiLogUid()
    {
        $tableName = ApiLog::tableName();
        $logs = ApiLog::find()->where(['l_action' => 'order_input', 'l_uid' => 0])->asArray()->all();
        $sql = "";
        foreach ($logs as $k => $v){
            $params = unserialize($v['l_params']);
            if (isset($params['uid'])){
                $uid = $params['uid'];
                $sql .= "UPDATE {$tableName} SET `l_uid` = {$uid} WHERE `l_id` = {$v['l_id']};";
            }
        }
        if (!$sql){
            return $sql;
        }
        $trans = \Yii::$app->db_app->beginTransaction();
        try{
            echo \Yii::$app->db_app->createCommand($sql)->execute();
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
    }

    /**
     * 提取手工图片
     * php yii others/db/refine-car-order-manual-pics
     */
    public function actionRefineCarOrderManualPics()
    {
        /**
         * @var CarOrder[] $car_orders
         */
        $car_orders = CarOrder::find()->all();
        foreach ($car_orders as $k => $v){
            $car_order = $v;
            $data = unserialize($v->serialize_data);
//            ManualPics::deleteAll(['custom_id' => $car_order->custom_id]);
            if (isset($data['req']['pics'])){
                $pics = $data['req']['pics'];
                foreach ($pics as $k1 => $v1){
                    $pic = $v1;
                    if ($pic['picid']<9000){
                        var_dump($pic['picid']);
                    }else{
                        $manual_pics = ManualPics::findOne(['custom_id' => $car_order->custom->id, 'picid' => $pic['picid'], 'picurl' => $pic['picurl']]);
                        if (!$manual_pics){
                            $manual_pics = new ManualPics();
                            $manual_pics->custom_id = $car_order->custom->id;
                            $manual_pics->picid = $pic['picid'];
                            $manual_pics->picurl = $pic['picurl'];
                            $manual_pics->created_at = time();
                            $manual_pics->picnote = isset($pic['picnote'])?$pic['picnote']:null;
                            $manual_pics->save();
                            echo "save";
                            var_dump($manual_pics->toArray());
                        }else{
                            echo "has";
                            var_dump($manual_pics->toArray());
                        }
                    }
                }
            }
        }
    }
}